import {
	defineStore
} from 'pinia';
import {
	basePinia
} from "./index.js";
import {
	planStore
} from '@/store/plan.js';
import {
	canDrawOverlays,
	setTopApp,
	wakeupAndUnlock
} from "@/utils/remindFn.js"
import {
	apiQueryPlan
} from "@/requestApi/plan.js";
import {
	formatDate
} from "@/utils/global.js"
export const usePinia = defineStore('remind', {
	state: () => {
		return {
			showRemind: false,
			remindTimer: null,
			curPlanList: [],
			showRemindData: {
				name: "",
				planDetail: "",
				startTime: "",
				endTime: "",
			}
		}
	},
	actions: {
		changeShowRemind(status) {
			this.showRemind = status
		},
		async setRemindTimer() {
			clearInterval(this.remindTimer)
			await remindStore.queryPlan()
			let tomorrowTime = this.getTomorrowTime()
			// console.log(tomorrowTime, 'v')
			this.remindTimer = setInterval(() => {
				let nowTime = parseInt(new Date().getTime() / 1000)
				// console.log(nowTime, 'nowTime')
				if (this.checkHasTime(this.curPlanList, nowTime)) {
					this.showRemindData = this.getHasTimeData(this.curPlanList, nowTime)
					// console.log(this.showRemindData, 'showRemindData', this.showRemind)
					this.changeShowRemind(true)
					console.log('showRemind', this.showRemind)
					setTopApp()
					uni.vibrateLong()
					clearInterval(this.remindTimer)
				}
				// 第二天重新设置定时器
				if (nowTime >= tomorrowTime) {
					this.setRemindTimer()
				}
			}, 1000)
		},
		checkHasTime(arr, startTime) {
			return arr.some(obj => obj.checkTime === startTime);
		},
		// 检查是否到了第二天
		getTomorrowTime() {
			const tomorrow = new Date();
			tomorrow.setDate(tomorrow.getDate() + 1);
			tomorrow.setHours(0, 0, 0, 0);
			return tomorrow.getTime() / 1000
		},
		// 获取匹配项数据
		getHasTimeData(arr, startTime) {
			for (let obj of arr) {
				if (obj.checkTime === startTime) {
					return obj;
				}
			}
			return null;
		},
		queryPlan(date) {
			return new Promise((resolve) => {
				if (!date) {
					date = formatDate(undefined, 1, 0)
					console.log(date, '---date')
				}
				let token = uni.getStorageSync("token")
				if (!!token) {
					apiQueryPlan(date).then(res => {
						// console.log(res.data, '------')
						if (res.code == 1 && res.data) {
							this.curPlanList = res.data.planList.map(e => {
								e.checkTime = new Date(`${e.startDate} ${e.startTime}`)
									.getTime() / 1000
								// e.checkTime = 1720976931
								// console.log(e.checkTime)
								return e
							});
							// console.log(this.curPlanList, 'planList--------')
						}
						resolve()
					}).catch(err => {
						console.log(err, 'err')
						resolve()
					})
				}
			})
		}
	},
	getters: {
		// $showRemind() {
		// 	console.log(this.showRemind, 'this.showRemind ')
		// 	return this.showRemind || false
		// }
	}
})

export const remindStore = usePinia(basePinia);